package com.leyou.user.interceptors;

import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.auth.utils.RsaUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.user.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author Eric
 * @version v1.0
 * @package com.leyou.user.interceptors
 * @date 2019/7/10 20:16
 * @description:
 **/
@Slf4j
public class PrivilegeInterceptor implements HandlerInterceptor {


    private JwtProperties prop;

    public PrivilegeInterceptor(JwtProperties prop) {
        this.prop = prop;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        try {
            String token = request.getHeader(prop.getApp().getHeaderName());
            Payload<AppInfo> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), AppInfo.class);

            AppInfo info = payload.getUserInfo();
            List<Long> targetList = info.getTargetList();

            if (targetList == null || !targetList.contains(prop.getApp().getId())) {
                // 没有访问权限，抛出异常
                throw new RuntimeException("请求者没有访问本服务的权限！");
            }

            log.info("服务{}，正在调用{}方法", info.getServiceName(), request.getRequestURI());
            return true;
        } catch (Exception e) {
            log.error("服务鉴权失败，原因：{}", e.getMessage(), e);
            throw new LyException(ExceptionEnum.UNAUTHORIZED,e);
        }
    }
}
